/*
 * Copyright (c) 2008 Kevin Wetzels
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
package be.roam.jindy.xml;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayDeque;
import java.util.Deque;

/**
 * Simple writer for XML.
 * 
 * @author Kevin Wetzels
 */
public class XmlWriter extends Writer {

	private Writer writer;

	private OutputStream os;

	private Charset charset;

	private boolean writingStartElement;

	private boolean writingEmptyElement;

	private Deque<String> stack;

	private boolean prettyPrint;

	/**
	 * Wrap an XML writer around the output stream, using the given charset.
	 * 
	 * @param os
	 *            output stream to wrap
	 * @param charset
	 *            charset to use
	 */
	public XmlWriter(OutputStream os, Charset charset) {
		this.os = os;
		this.charset = (charset == null ? Charset.forName("UTF-8") : charset);
		this.stack = new ArrayDeque<String>(8);
	}

	/**
	 * Returns <code>true</code> when pretty-printing is enabled.
	 * 
	 * @return <code>true</code> when pretty-printing is enabled
	 */
	public boolean isPrettyPrint() {
		return prettyPrint;
	}

	/**
	 * Enable or disable pretty printing (defaults to <code>false</code>).
	 * 
	 * @param prettyPrint
	 *            set to <code>true</code> to enable
	 */
	public void setPrettyPrint(boolean prettyPrint) {
		this.prettyPrint = prettyPrint;
	}

	@Override
	public void close() throws IOException {
		getWriter().close();
	}

	@Override
	public void flush() throws IOException {
		getWriter().flush();
	}

	/**
	 * Writes the XML declaration.
	 * 
	 * @return the current instance (for chaining)
	 * @throws IOException
	 */
	public XmlWriter writeDeclaration() throws IOException {
		getWriter().write("<?xml version=\"1.0\" encoding=\"" + charset.name() + "\"?>");
		return this;
	}

	/**
	 * Starts writing an element.
	 * 
	 * @param element
	 *            element to start
	 * @return the current instance (for chaining)
	 * @throws IOException
	 */
	public XmlWriter start(String element) throws IOException {
		closeOpenStartTag();
		writingStartElement = true;
		stack.push(element);
		return plain(prettyPrintString(false) + "<" + element);
	}

	/**
	 * Writes an empty element.
	 * 
	 * @param element
	 *            element to write
	 * @return the current instance (for chaining)
	 * @throws IOException
	 */
	public XmlWriter empty(String element) throws IOException {
		closeOpenStartTag();
		writingStartElement = true;
		writingEmptyElement = true;
		stack.push(element);
		return plain(prettyPrintString(false) + "<" + element);
	}

	/**
	 * Writes text.
	 * 
	 * @param text
	 *            text to write
	 * @return the current instance (for chaining)
	 * @throws IOException
	 */
	public XmlWriter text(String text) throws IOException {
		closeOpenStartTag();
		return escape(prettyPrintString(true) + text);
	}
	
	public XmlWriter cdata(String text) throws IOException {
		closeOpenStartTag();
		return plain("<![CDATA[" + text.replace("]]>", "]]]]><![CDATA[>") + "]]>");
	}

	/**
	 * Closes an element.
	 * 
	 * @return the current instance (for chaining)
	 * @throws IOException
	 */
	public XmlWriter end() throws IOException {
		closeOpenStartTag();
		return plain(prettyPrintString(false) + "</" + stack.pop() + ">");
	}

	/**
	 * Adds an attribute to the element.
	 * 
	 * @param key
	 *            key of the attribute
	 * @param value
	 *            value of the attribute
	 * @return the current instance (for chaining)
	 * @throws IOException
	 */
	public XmlWriter attribute(String key, String value) throws IOException {
		return plain(" " + key + "=\"").escape(value).plain("\"");
	}

	private XmlWriter plain(String string) throws IOException {
		getWriter().write(string);
		return this;
	}

	private XmlWriter escape(String string) throws IOException {
		XmlUtils.escape(getWriter(), string);
		return this;
	}

	private XmlWriter closeOpenStartTag() throws IOException {
		if (writingEmptyElement) {
			plain("/");
			stack.pop();
			writingEmptyElement = false;
		}
		if (writingStartElement) {
			plain(">");
			writingStartElement = false;
		}
		return this;
	}

	private String prettyPrintString(boolean isContent) {
		if (!prettyPrint) {
			return "";
		}
		int length = stack.size() + (isContent ? 0 : -1);
		String string = "\n";
		for (int index = 0; index < length; ++index) {
			string += "  ";
		}
		return string;
	}

	@Override
	public void write(char[] cbuf, int off, int len) throws IOException {
		getWriter().write(cbuf, off, len);
	}

	private Writer getWriter() {
		if (writer == null) {
			writer = new BufferedWriter(new OutputStreamWriter(os, charset));
		}
		return writer;
	}

}
